package com.dfcj.oauth2security.configure;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;


import javax.servlet.http.HttpServletResponse;

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceConfig extends ResourceServerConfigurerAdapter {
    @Autowired
    private MyAccessDecisionManager myAccessDecisionManager;

    @Override
    public void configure(HttpSecurity http) throws Exception {

//        http
//                .csrf().disable()
//                .exceptionHandling()
//                .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
//                .and()
//                .requestMatchers()
//                .antMatchers("/hello","/hello/**")
//                .and()
//                .authorizeRequests()
//                .antMatchers("/hello","/hello/**")
//                .authenticated()
//                .and()
//                .formLogin().permitAll();
        http
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
                .and()
//                .requestMatchers()
//                .antMatchers("/hello","/hello/**")
//                .and()
                .authorizeRequests()
                .antMatchers("/hello","/hello/**").authenticated().accessDecisionManager(myAccessDecisionManager)
//                .and()
//                .authorizeRequests()
//                .antMatchers("/hello","/hello/**").authenticated()
//                .and()
//                .authorizeRequests()
//                .antMatchers("/hello","/hello/**").hasAuthority(null)
                .and()
                .authorizeRequests()
                .antMatchers("/actuator/**", "/oauth/**","/token/**").permitAll()
                .and()
                .formLogin().permitAll();
    }
}
